package com.jeomo.sys.starter.service.impl;

import com.jeomo.base.starter.service.impl.BaseServiceImpl;
import com.jeomo.sys.starter.entity.Permission;
import com.jeomo.sys.starter.entity.Role;
import com.jeomo.sys.starter.entity.RolePermission;
import com.jeomo.sys.starter.mapper.RoleMapper;
import com.jeomo.sys.starter.mapper.RolePermissionMapper;
import com.jeomo.sys.starter.service.IRoleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author jeomo
 * @since 2019-03-22
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<RoleMapper, Role> implements IRoleService {

    @Resource
    RolePermissionMapper rolePermissionMapper;

    @Override
    public List<Role> listGroup(String topCode) {
        return this.baseMapper.listGroup(topCode);
    }

    @Override
    public boolean savePermissions(String roleCode, List<String> permissions) {
        rolePermissionMapper.deleteByRoleCode(roleCode);
        for(String permissionCode : permissions) {
            rolePermissionMapper.insert(new RolePermission(roleCode, permissionCode));
        }
        return false;
    }

    @Override
    public List<Role> selectByUserCode(String userCode) {
        return baseMapper.selectByUserCode(userCode);
    }

    @Override
    public int deleteByUserCode(String userCode) {
        return baseMapper.deleteByUserCode(userCode);
    }


    /**
     * 重新保存方法
     * 保存的同时，插入角色权益中间表信息
     * @param role
     * @return
     */
    @Override
    public boolean save(Role role) {
        super.save(role);
        saveRolePermissions(role);
        return true;
    }

    @Override
    public boolean updateById(Role role) {
        boolean result = super.updateById(role);
        rolePermissionMapper.deleteByRoleCode(role.getCode());
        saveRolePermissions(role);
        return false;
    }

    /**
     * 保存角色的权限信息
     * @param role
     */
    private void saveRolePermissions(Role role) {
        if(role.getPermissions() != null) {
            for(Permission permission : role.getPermissions()) {
                RolePermission rolePermission = new RolePermission();
                rolePermission.setRoleCode(role.getCode());
                rolePermission.setPermissionCode(permission.getCode());
                rolePermissionMapper.insert(rolePermission);
            }
        }
    }
}
